/*
 * @lc app=leetcode.cn id=748 lang=typescript
 *
 * [748] 最短补全词
 */

// @lc code=start
function shortestCompletingWord(licensePlate: string, words: string[]): string {
    const temp = sumOfChar(licensePlate);

    let result!: string;
    for (const iterator of words) {
        if (isValidMap(iterator, temp)) {
            if (result === undefined) result = iterator;
            if (result.length > iterator.length) result = iterator;
        }
    }

    return result!;
}
const sumOfChar = (s: string) => {
    let map = new Map<string, number>();
    s.split("").forEach((i) => {
        if (isEn(i))
            map.set(i.toLowerCase(), (map.get(i.toLowerCase()) || 0) + 1);
    });
    return map;
};
const isValidMap = (s: string, map: Map<string, number>) => {
    const newMap = sumOfChar(s);
    return [...map.entries()].every(([key, val]) => {
        const newVal = newMap.get(key);
        if (typeof newVal === "number") {
            return newVal >= val;
        }
        return false;
    });
};
const isEn = (s: string) => {
    const code = s.charCodeAt(0);
    return (
        (code >= "a".charCodeAt(0) && code <= "z".charCodeAt(0)) ||
        (code >= "A".charCodeAt(0) && code <= "Z".charCodeAt(0))
    );
};
// @lc code=end
